package net.jgrm.product.service.impl;

import net.jgrm.product.entity.Product;
import net.jgrm.product.service.IProductService;
import net.jgrm.product.service.IProductStockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 商品综合服务实现（简化版）
 * <p>
 * 职责：组合 ProductService 和 ProductStockService 的数据
 * <p>
 * 优化后的架构：
 * 1. ProductService：管理 product-info 缓存
 * 2. ProductStockService：管理 product-stock 缓存
 * 3. 此服务：仅负责数据组合，不涉及额外缓存
 *
 * @author jgrm
 */
@Service
public class ProductBaseInfoService {

    private static final Logger logger = LoggerFactory.getLogger(ProductBaseInfoService.class);

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductStockService productStockService;

    /**
     * 获取完整商品信息（基本信息 + 实时库存）
     * 组合两个服务的缓存数据
     */
    public Product getCompleteProductInfo(Long id) {
        logger.info("Getting complete product info for: {}", id);

        // 1. 获取商品基本信息（命中 product-info 缓存）
        Product product = productService.getProductById(id);
        if (product == null) {
            throw new RuntimeException("商品不存在: " + id);
        }

        // 2. 获取实时库存（命中 product-stock 缓存）
        Integer stock = productStockService.getStock(id);
        product.setStock(stock);

        logger.debug("Successfully combined product info and stock for: {}", id);
        return product;
    }

    /**
     * 批量获取完整商品信息
     */
    public List<Product> getCompleteProductInfoByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }

        logger.info("Getting complete product info for {} products", ids.size());

        List<Product> result = new ArrayList<>();
        for (Long id : ids) {
            try {
                Product product = getCompleteProductInfo(id);  // 复用缓存
                result.add(product);
            } catch (Exception e) {
                logger.warn("Failed to get product info for id {}: {}", id, e.getMessage());
            }
        }

        return result;
    }
}